package syM

import (
	"database/sql"
	"github.com/panjf2000/ants/v2"
	"db2s/Er"
	metaD "db2s/MetaInit"
	"db2s/arg"
	cp "db2s/componentInit"
	"db2s/global"
	"db2s/outPut"
	"db2s/parDef"
	"db2s/pubM"
	quit "db2s/quitDispos"
	mq "db2s/topic-mq"
	"os"
	"reflect"
	"sync"
	"time"
)

var (
	//wLog                  *log.Logger
	continueTableList     = make(map[string]int)
	ChanSchedulePlanTable chan any
	baseMsgSendBody       mq.MonitorMsgMq
	schemaDataFixFileName string
	schemaDataFixPoint    outPut.FileOperations
	meta                  *CheckSchemaMetaData
)

const (
	singleQueryMessageQueueLength int = 1
)

type (
	InitDSnsPoolResult struct {
		SDB, DDB                                           map[string]*sql.DB
		SMS, SMScurry, DMS, DMScurry                       map[string]int64
		SrcModifyParameterRecode, DstModifyParameterRecode []global.ModifyParameterResultS
	}
)

type (
	//schemaGroupFilter *TableMetaDataInit.SchemaInitObject
	schemaInitContext SchemaInitContext
	// Topic 自定义Topic 类型 限制范围 避免出错
	Topic string
	Logo  string //dataFix Type 标识
	// CheckObject 自定义CheckObject 类型 限制范围 避免出错
	CheckObject string
	CheckMode   string // CheckMode
	IndexType   string //Index type distinction
	Keywords    string //data split keyword
)

const (
	StructIsBaseQuery      Topic = "StructIsBaseQuery"
	StructIsColumnMeta     Topic = "StructIsColumnMeta"
	StructIsIndexMeta      Topic = "StructIsIndexMeta"
	StructIsPartMeta       Topic = "StructIsPartMeta"
	StructIsMetaComparison Topic = "StructIsMetaComparison"
	StructIsFix            Topic = "StructIsFix"
	StructIsApply          Topic = "StructIsApply"
)
const (
	ObjectBaseQuery        Topic = "ObjectBaseQuery"
	ObjectIsJobMeta        Topic = "ObjectIsJobMeta"
	ObjectIsViewMeta       Topic = "ObjectIsViewMeta"
	ObjectIsProcedureMeta  Topic = "ObjectIsProcedureMeta"
	ObjectIsFuncMeta       Topic = "ObjectIsFuncMeta"
	ObjectIsTriggerMeta    Topic = "ObjectIsTriggerMeta"
	ObjectIsPackageMeta    Topic = "ObjectIsPackageMeta"
	ObjectIsTypeMeta       Topic = "ObjectIsTypeMeta"
	ObjectIsForeignMeta    Topic = "ObjectIsForeignMeta"
	ObjectIsSeqMeta        Topic = "ObjectIsSeqMeta"
	ObjectIsMetaComparison Topic = "ObjectIsMetaComparison"
	ObjectIsFix            Topic = "ObjectIsFix"
	ObjectIsApply          Topic = "ObjectIsApply"
)

var (
	lock            sync.Mutex
	SchemaContext   *schemaInitContext
	PlanContext     *SchedulePlanContext
	GlobalPConfigs  *GlobalParametersConfig
	GlobalISObjects *GlobalISObject
	closeObject     quit.Close
	//producer 生产者
	producer mq.Producer
	//consumer 消费者
	consumer                mq.Consumer
	FuncRef                 map[string]reflect.Value
	ScheduleTaskInitFuncRef map[string]reflect.Value
	MqListenerSInitFunc     map[string]reflect.Value
)

type (
	SchemaInitContextConfig struct {
		TableList     []string            //表对象清单
		GtCheckConfig arg.ConfigParameter //客户端传参
	}
	// GlobalISObject 全局表结构或结构初始化对象
	GlobalISObject struct {
		TableMetaData map[string]Er.TablesMetaInfoEr
	}
	ReadWriteFilePointS struct {
		ParameterRecord *os.File
		BreakPointFin   *os.File
		ActiveDataFin   *os.File
		TtyBarFin       *os.File
		ObjectResult    *os.File
	}
	GlobalParametersConfig struct { // SchedulePlanConfig 输入参数重新复制
		TableList []string
		FilePoint ReadWriteFilePointS
		TableObject []*arg.InputTableAttributes
		repair      arg.RepairS
		result      arg.Result
		rules       arg.RulesS
		dSns        arg.DSNsS
		structs     arg.StructS
		db          pubM.Conn
	}
	CheckSchemaMetaData struct {
		TableMD               []*metaD.TableMeta
		TableObject           []*arg.InputTableAttributes
		TableObjectFlow       chan any
		ObjectSum             int
		IgnoreObjectSum       int64
		schemaMetaMsgSendBody *mq.MonitorMsgMq
	}
	SchedulePlanContextConfig struct {
		TableList     []string
		BeginTime     time.Time
		GtCheckConfig arg.ConfigParameter
		MQConfig      *cp.MQConfig
	}
	TableAllColumnInfoS struct {
		SColumnInfo    []map[string]string //表的所有列信息
		DColumnInfo    []map[string]string //表的所有列信息
		Schema         string
		Table          string
		IndexColumnSeq map[string]string
		ColumnSeq      map[string]string
		MapTable       map[string]string
		IndexType      string
		IndexColumn    []string
	}
	mqProductCustomerMonitorMessage struct {
		mqProductSeq           *int64 //生产者信息
		mqCustomerSeq          *int64 //消费者数据记录
		ProductMessage         chan map[string][]string
		mqStartTiming          *int64
		mqLevelProductSend     *int64 //level 1生成的总数
		mqLevelCustomerReceive *int64
	}
	DataFixFile struct {
		BasePath        string
		CreateFileName  string
		AlterFileName   string
		AlterFilePoint  outPut.FileOperations
		CreateFilePoint outPut.FileOperations
		SchemaFileName  string
		SchemaFilePoint outPut.FileOperations
	}
	// SchedulePlan2 执行计划操作对象
	SchedulePlan2 struct {
		Object                     global.Object
		SrcParameter, DstParameter parDef.Parameter
		MQ                         *mq.MonitorMsgMq
		repair                     arg.RepairS
		fixFile                    DataFixFile
		Status                     global.TableStatus
		rules                      arg.RulesS
		tableColData               TableAllColumnInfoS
		subTaskInfo                *mq.SubTasks
		TPod                       *outPut.TPod
		XlsTerminal                *outPut.WorkSheetTerminal
		XlsSwitch                  *outPut.WorkSheetSwitch
		XlsResult                  *outPut.WorkSheetResult
		XlsMiss                    *outPut.WorkSheetMiss
		subTaskBeginTime           int64
		SpeedLimitMonitor          *mq.SpeedLimitMonitor
		//structS                  global.StructPlan
		TableAttributes          arg.TableSubOptions
		mqProductCustomerMonitor mqProductCustomerMonitorMessage
	}
	TableObjectMiss struct {
		ObjectLogSeq int64
		ObjectName   string
	}
	// SchedulePlanContext 执行计划上下文
	SchedulePlanContext struct {
		//多任务执行计划
		ChanSchedulePlanTable chan any //[]map[string] /*SchemaToTable*/ *SchedulePlan2
		//存储执行计划任务
		SchedulePlanTable any //map[string] /*SchemaToTable*/ *SchedulePlan2
		// 上下文任务线程池
		Pool *ants.Pool
		//自动关闭mq的组件
		AutoCloseMqComponentTable map[cp.CheckMode]*cp.AutoCloseMqComponent
		//进度条
		TaskBarTable *mq.TaskBar
		Rw           sync.Mutex
		BeginTime    time.Time
		wg           sync.WaitGroup
		TableMiss    chan TableObjectMiss
	}
	// SchemaInitContext 执行计划上下文
	SchemaInitContext struct {
		Seq     int
		Schema  string
		Table   string
		MSchema string
		MTable  string
		TableMiss         bool
		ObjectLogSeq      int64
		TColumnMeta       global.TableMetaGather
		IndexData         metaD.IndexChooseResult
		Role              string
		TableSum          int
		IgnoreObjectSum   int64
		TableFree         *int64
		BreakPointSum     *int64
		TableAttributes   arg.TableSubOptions
		TableAccount      *int64
		ChanSchemaContext chan any
		TPod              *outPut.TPod
	}
	//AutoCloseMqComponent 自动关闭mq的组件
	AutoCloseMqComponent struct {
		TopicStatistics  map[Topic]*int64
		UnsubscribeTopic []Topic
		CheckMode        CheckMode
		EndMark          bool
	}
)
type FixSqlResult struct {
	Sql    string
	AbInfo string
}

type fixSqlResult struct {
	createSql any
	printSql  any
}
type (
	initGlobalResultFileReturnResult struct {
		breakPointFin *os.File
		activeDataFin *os.File
		ttyBarFin     *os.File
		objectResult  *os.File
	}
)
